const mongoose = require('mongoose');
const db = 'mongodb://localhost/shop';

// 引入 Schema
const glob = require('glob');
const path = require('path');

// 导出 Schema
exports.initSchemas = () => {
  glob.sync(path.resolve(__dirname, './model', '*.js')).forEach(require);
};

// 导出数据库连接
exports.connect = () => {
  mongoose.set('useCreateIndex', true);

  // 连接数据库 (兼容配置)
  mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });

  // 监听数据库连接
  mongoose.connection.on('disconnected', () => {
    mongoose.connect(db);
  });

  // 数据库出现错误
  mongoose.connection.on('error', (err) => {
    console.log(err);
    mongoose.connect(db);
  });

  // 数据库连接成功
  mongoose.connection.once('open', () => {
    console.log('mongodb connect success');
  });
};
